define(function(require,exports,module){
	
	
	//证件列表
	$.ajax({
		url:"/member/usercertification/fileType.html?randomTime=" + (new Date()).getTime(),
		type:"get",
		dataType:"json",
		success:function(data){
			var tpl = require('/themes/theme_default/media/tpl/member/usercertification_fileType.tpl');//载入tpl模板
			var template = Handlebars.compile(tpl);
			var html = template(data);
			$(".user_filesList_tab").html(html);
			//默认选中第一个标签
			$(".user_filesList_tab li").eq(0).addClass("hover");
			getPicList($(".user_filesList_tab  .hover").attr("data-id"));
						
			//标签切换
			$(".user_filesList_tab li").click(function(){
				$(this).addClass("hover").siblings().removeClass("hover");
				var fileType = $(this).attr("data-id");
				getPicList(fileType);
			});
		}
	})
	//获取图片列表
	function getPicList(id){
		$.ajax({
			url:"/member/usercertification/filesList.html?tid=" + id + "&randomTime=" + (new Date()).getTime(),
			type:"get",
			dataType:"json",
			success:function(data){
				var picTpl = require('/themes/theme_default/media/tpl/member/usercertification_fliePicList.tpl');//载入tpl模板
				var template = Handlebars.compile(picTpl);
				var html = template(data);
				$(".user_filesList_content ul").html(html);
			}
		})
	}
	
	//上传图片
	$(".addFile").live('click',function(){
		require.async(['/plugins/layer-v1.8.4/skin/layer.css','/plugins/layer-v1.8.4/layer.min'],function(){
			//加载弹出框
			$.layer({
			    type: 1,
			    closeBtn: [0, true],
			    title: '上传资料',
			    area: ['550px', '450px'],
			    border: [10, 0.2, '#545454'],
			    page : {
			    	html:'<div id="uploader"><div class="queueList"><div id="dndArea" class="placeholder"><div id="filePicker"></div><p>支持GIF,JPG,PNG图片格式</p></div></div><div class="statusBar" style="display:none;"><div class="progress">	<span class="text">0%</span><span class="percentage"></span></div><div class="info"></div><div class="btns"><div id="filePicker2"></div><div class="uploadBtn">开始上传</div></div></div></div>'
			    }
			});
						
			//加载上传控件
			require.async(['/plugins/webuploader-0.1.5/webuploader','/plugins/webuploader-0.1.5/webuploader.css'],function(){
				var $ = jQuery;
					$wrap = $('#uploader'),
	
			        // 图片容器
			        $queue = $('<ul class="filelist"></ul>')
			            .appendTo( $wrap.find('.queueList') ),
	
			        // 状态栏，包括进度和控制按钮
			        $statusBar = $wrap.find('.statusBar'),
	
			        // 文件总体选择信息。
			        $info = $statusBar.find('.info'),
	
			        // 上传按钮
			        $upload = $wrap.find('.uploadBtn'),
	
			        // 没选择文件之前的内容。
			        $placeHolder = $wrap.find('.placeholder'),
	
			        // 总体进度条
			        $progress = $statusBar.find('.progress').hide(),
	
			        // 添加的文件数量
			        fileCount = 0,
	
			        // 添加的文件总大小
			        fileSize = 0,
	
			        // 优化retina, 在retina下这个值是2
			        ratio = window.devicePixelRatio || 1,
	
			        // 缩略图大小
			        thumbnailWidth = 110 * ratio,
			        thumbnailHeight = 110 * ratio,
	
			        // 可能有pedding, ready, uploading, confirm, done.
			        state = 'pedding',
	
			        // 所有文件的进度信息，key为file id
			        percentages = {},
	
			        supportTransition = (function(){
			            var s = document.createElement('p').style,
			                r = 'transition' in s ||
			                      'WebkitTransition' in s ||
			                      'MozTransition' in s ||
			                      'msTransition' in s ||
			                      'OTransition' in s;
			            s = null;
			            return r;
			        })(),
	
			        // WebUploader实例
			        uploader;
	
			    if ( !WebUploader.Uploader.support() ) {
			        alert( 'Web Uploader 不支持您的浏览器！如果你使用的是IE浏览器，请尝试升级 flash 播放器');
			        throw new Error( 'WebUploader does not support the browser you are using.' );
			    }
	
			    // 实例化
			    uploader = WebUploader.create({
			        pick: {
			            id: '#filePicker',
			            label: '选择图片'
			        },
			        dnd: '#uploader .queueList',
			        paste: document.body,
	
			        accept: {
			            title: 'Images',
			            extensions: 'gif,jpg,jpeg,png',
			            mimeTypes: 'image/*'
			        },
	
			        // swf文件路径
			        swf:'/plugins/webuploader-0.1.5/Uploader.swf' ,
			        disableGlobalDnd: true,
			        chunked: true,
			        server: '/member/usercertification/fileUpload.html',
			        fileNumLimit: 8,
			        fileSizeLimit: 5 * 1024 * 1024,    // 200 M
			        fileSingleSizeLimit: 1 * 1024 * 1024,    // 50 M
			        runtimeOrder:"flash",
			        formData: {tid : $(".user_filesList_tab li.hover").attr("data-id")},
			        fileVal:"file"
			    });
			    // 添加“添加文件”的按钮，
			    uploader.addButton({
			        id: '#filePicker2',
			        label: '继续添加'
			    })
			    
			 // 当有文件添加进来时执行，负责view的创建
			    function addFile( file ) {
			        var $li = $( '<li id="' + file.id + '">' +
			                '<p class="title">' + file.name + '</p>' +
			                '<p class="imgWrap"></p>'+
			                '<p class="progress"><span></span></p>' +
			                '</li>' ),

			            $btns = $('<div class="file-panel">' +
			                '<span class="cancel">删除</span>' +
			                '<span class="rotateRight">向右旋转</span>' +
			                '<span class="rotateLeft">向左旋转</span></div>').appendTo( $li ),
			            $prgress = $li.find('p.progress span'),
			            $wrap = $li.find( 'p.imgWrap' ),
			            $info = $('<p class="error"></p>'),

			            showError = function( code ) {
			                switch( code ) {
			                    case 'exceed_size':
			                        text = '文件大小超出';
			                        break;

			                    case 'interrupt':
			                        text = '上传暂停';
			                        break;

			                    default:
			                        text = '上传失败，请重试';
			                        break;
			                }
			                $info.text( text ).appendTo( $li );
			            };

			        if ( file.getStatus() === 'invalid' ) {
			            showError( file.statusText );
			        } else {
			            // @todo lazyload
			            $wrap.text( '预览中' );
			            uploader.makeThumb( file, function( error, src ) {
			                if ( error ) {
			                    $wrap.text( '不能预览' );
			                    return;
			                }

			                var img = $('<img src="'+src+'">');
			                $wrap.empty().append( img );
			            }, thumbnailWidth, thumbnailHeight );

			            percentages[ file.id ] = [ file.size, 0 ];
			            file.rotation = 0;
			        }

			        file.on('statuschange', function( cur, prev ) {
			            if ( prev === 'progress' ) {
			                $prgress.hide().width(0);
			            } else if ( prev === 'queued' ) {
			                $li.off( 'mouseenter mouseleave' );
			                $btns.remove();
			            }

			            // 成功
			            if ( cur === 'error' || cur === 'invalid' ) {
			                console.log( file.statusText );
			                showError( file.statusText );
			                percentages[ file.id ][ 1 ] = 1;
			            } else if ( cur === 'interrupt' ) {
			                showError( 'interrupt' );
			            } else if ( cur === 'queued' ) {
			                percentages[ file.id ][ 1 ] = 0;
			            } else if ( cur === 'progress' ) {
			                $info.remove();
			                $prgress.css('display', 'block');
			            } else if ( cur === 'complete' ) {
			                $li.append( '<span class="success"></span>' );
			            }

			            $li.removeClass( 'state-' + prev ).addClass( 'state-' + cur );
			        });

			        $li.on( 'mouseenter', function() {
			            $btns.stop().animate({height: 30});
			        });

			        $li.on( 'mouseleave', function() {
			            $btns.stop().animate({height: 0});
			        });

			        $btns.on( 'click', 'span', function() {
			            var index = $(this).index(),
			                deg;

			            switch ( index ) {
			                case 0:
			                    uploader.removeFile( file );
			                    return;

			                case 1:
			                    file.rotation += 90;
			                    break;

			                case 2:
			                    file.rotation -= 90;
			                    break;
			            }

			            if ( supportTransition ) {
			                deg = 'rotate(' + file.rotation + 'deg)';
			                $wrap.css({
			                    '-webkit-transform': deg,
			                    '-mos-transform': deg,
			                    '-o-transform': deg,
			                    'transform': deg
			                });
			            } else {
			                $wrap.css( 'filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+ (~~((file.rotation/90)%4 + 4)%4) +')');
			            }


			        });

			        $li.appendTo( $queue );
			    }

			    // 负责view的销毁
			    function removeFile( file ) {
			        var $li = $('#'+file.id);

			        delete percentages[ file.id ];
			        updateTotalProgress();
			        $li.off().find('.file-panel').off().end().remove();
			    }

			    function updateTotalProgress() {
			        var loaded = 0,
			            total = 0,
			            spans = $progress.children(),
			            percent;

			        $.each( percentages, function( k, v ) {
			            total += v[ 0 ];
			            loaded += v[ 0 ] * v[ 1 ];
			        } );

			        percent = total ? loaded / total : 0;

			        spans.eq( 0 ).text( Math.round( percent * 100 ) + '%' );
			        spans.eq( 1 ).css( 'width', Math.round( percent * 100 ) + '%' );
			        updateStatus();
			    }

			    function updateStatus() {
			        var text = '', stats;

			        if ( state === 'ready' ) {
			            text = '选中' + fileCount + '张图片，共' +
			                    WebUploader.formatSize( fileSize ) + '。';
			        } else if ( state === 'confirm' ) {
			            stats = uploader.getStats();
			            if ( stats.uploadFailNum ) {
			                text = '已成功上传' + stats.successNum+ '张，'+
			                    stats.uploadFailNum + '张上传失败，<a class="retry" href="#">重新上传</a>失败图片或<a class="ignore" href="#">忽略</a>'
			            }

			        } else {
			            stats = uploader.getStats();
			            text = '共' + fileCount + '张（' +
			                    WebUploader.formatSize( fileSize )  +
			                    '），已上传' + stats.successNum + '张';

			            if ( stats.uploadFailNum ) {
			                text += '，失败' + stats.uploadFailNum + '张';
			            }
			        }

			        $info.html( text );
			    }

			    function setState( val ) {
			        var file, stats;

			        if ( val === state ) {
			            return;
			        }

			        $upload.removeClass( 'state-' + state );
			        $upload.addClass( 'state-' + val );
			        state = val;

			        switch ( state ) {
			            case 'pedding':
			                $placeHolder.removeClass( 'element-invisible' );
			                $queue.parent().removeClass('filled');
			                $queue.hide();
			                $statusBar.addClass( 'element-invisible' );
			                uploader.refresh();
			                break;

			            case 'ready':
			                $placeHolder.addClass( 'element-invisible' );
			                $( '#filePicker2' ).removeClass( 'element-invisible');
			                $queue.parent().addClass('filled');
			                $queue.show();
			                $statusBar.removeClass('element-invisible');
			                uploader.refresh();
			                break;

			            case 'uploading':
			                $( '#filePicker2' ).addClass( 'element-invisible' );
			                $progress.show();
			                $upload.text( '暂停上传' );
			                break;

			            case 'paused':
			                $progress.show();
			                $upload.text( '继续上传' );
			                break;

			            case 'confirm':
			                $progress.hide();
			                $upload.text( '开始上传' ).addClass( 'disabled' );

			                stats = uploader.getStats();
			                if ( stats.successNum && !stats.uploadFailNum ) {
			                    setState( 'finish' );
			                    return;
			                }
			                break;
			            case 'finish':
			                stats = uploader.getStats();
			                if ( stats.successNum ) {
			                	//关闭当前窗口
			                	layer.closeAll();
			                	//重新获取当前类型的图片列表
			                	var fileType = $(".user_filesList_tab  .hover").attr("data-id");
			                	$.post("/member/usercertification/certificationApply.html", { "typeId": fileType });
			                	getPicList(fileType);	
			                } else {
			                    // 没有成功的图片，重设
			                    state = 'done';
			                    location.reload();
			                }
			                break;
			        }

			        updateStatus();
			    }

			    uploader.onUploadProgress = function( file, percentage ) {
			        var $li = $('#'+file.id),
			            $percent = $li.find('.progress span');

			        $percent.css( 'width', percentage * 100 + '%' );
			        percentages[ file.id ][ 1 ] = percentage;
			        updateTotalProgress();
			    };

			    uploader.onFileQueued = function( file ) {
			        fileCount++;
			        fileSize += file.size;

			        if ( fileCount === 1 ) {
			            $placeHolder.addClass( 'element-invisible' );
			            $statusBar.show();
			        }

			        addFile( file );
			        setState( 'ready' );
			        updateTotalProgress();
			    };

			    uploader.onFileDequeued = function( file ) {
			        fileCount--;
			        fileSize -= file.size;

			        if ( !fileCount ) {
			            setState( 'pedding' );
			        }

			        removeFile( file );
			        updateTotalProgress();

			    };

			    uploader.on( 'all', function( type ) {
			        var stats;
			        switch( type ) {
			            case 'uploadFinished':
			                setState( 'confirm' );
			                break;

			            case 'startUpload':
			                setState( 'uploading' );
			                break;

			            case 'stopUpload':
			                setState( 'paused' );
			                break;

			        }
			    });

			    uploader.onError = function( code ) {
			        if(code =="F_DUPLICATE"){
			        	layer.msg('图片已存在', 1, -1);
			        }else if(code =="Q_EXCEED_NUM_LIMIT"){
			        	layer.msg('图片上传数超出', 1, -1);
			        }else if(code=="Q_EXCEED_SIZE_LIMIT"){
			        	layer.msg('图片文件总大小超出', 1, -1);
			        }else if(code=="Q_TYPE_DENIED"){
			        	layer.msg('仅支持GIF,JPG,PNG图片格式', 1, -1);
			        }
			    };

			    $upload.on('click', function() {
			        if ( $(this).hasClass( 'disabled' ) ) {
			            return false;
			        }

			        if ( state === 'ready' ) {
			            uploader.upload();
			        } else if ( state === 'paused' ) {
			            uploader.upload();
			        } else if ( state === 'uploading' ) {
			            uploader.stop();
			        }
			    });

			    $info.on( 'click', '.retry', function() {
			        uploader.retry();
			    } );

			    $info.on( 'click', '.ignore', function() {
			        //alert( 'todo' );
			    } );

			    $upload.addClass( 'state-' + state );
			    updateTotalProgress();
			    
			    
			})
		})
	})
	
	
	//删除图片
	$(".user_filesList_content").delegate(".fileclose","click",function(){
		var idVal=$(this).attr("data-id");
		var current = $(this);
		require.async(['/plugins/layer-v1.8.4/skin/layer.css','/plugins/layer-v1.8.4/layer.min'],function(){
			//构造确认框DOM
			$.layer({
			    type: 1,
			    closeBtn: false,
			    title: false,
			    area: ['460px', '240px'],
			    border: [10, 0.2, '#545454'],
			    page: {
			        html: '<div class="fileconfirm"><div class="fileconfirm_title"><h1 class="float_left">删除提示</h1><span class="float_right closeBtn">X</span></div><div class="fileconfirm_msg"><span><i class="iconfont">&#xe614;</i>确定要删除该资料吗？</span></div><div class="fileconfirmbtn"><a href="javascript:;" class="okBtn">确定</a><a href="javascript:;"  class="cancleBtn closeBtn">取消</a></div></div>'
			    }
			});	
			//确认操作
			$(".okBtn").click(function(){
				$.ajax({
					url:"/member/usercertification/fileDel.html?id=" + idVal + "&randomTime=" + (new Date()).getTime(),
					dataType:"json",
					success: function(data){
						if(data.result){
							current.parent("li").remove();
							layer.closeAll();
						}else{
							layer.msg('系统错误！', 1, -1);
						}						
					}			
				});				
			});
			//删除操作
			$(".closeBtn").click(function(){
				layer.closeAll();
			});
		}); 
	});
	
	//预览图片
	require.async(['/plugins/fancybox/jquery.fancybox.css','/plugins/fancybox/jquery.fancybox.pack'],function(){
		$(".fileshow").fancybox(/*{
			afterLoad: function() {
		        this.title = '<div class="fileViewTitle"><span><b>资料类型：</b>'+ this.title +'</span><span class="flieUpTime"><b>上传时间：</b>'+ $(this.element).attr('data-time'); + '</span></div>';
		    },
		    helpers : {
		        title: {
		            type: 'inside'
		        }
		    }
		}*/);
	});
});